//
//  ArtTopicDetailListViewController.m
//  ArtOfLiving
//
//  Created by 王文晓 on 16/4/30.
//  Copyright © 2016年 刘虎. All rights reserved.
//

#import "ArtTopicDetailListViewController.h"
#import "GoOutSpecialTopicDetialViewController.h"
#import "ArtTopicVideoViewController.h"
#import "ArtTopicDetailListViewCell.h"
#import "ArtTopicListModel.h"
#import "ArtTopDataModel.h"


@interface ArtTopicDetailListViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;           //tableView
@property (nonatomic, strong) NSMutableArray *dataSourceMArr;   //存储Model的数组
@property (nonatomic, strong) NSMutableDictionary *parameter;   //参数字典
@property (nonatomic, strong) NSMutableArray *timeRankMArr;     //按时间排序的传值数组
@property (nonatomic, strong) NSMutableArray *shareRankingMArr; //按分享排行的传值数组
@property (nonatomic, strong) NSMutableArray *categoryIdMArr;   //categoryId传值数组
@property (nonatomic, assign) int start;                        //设置加载条数
@property (nonatomic, strong) UISegmentedControl *segmentedControl; //分段控制器
@property (nonatomic, strong) LHSelectedNavigationViewTools *selected; //自定义顶部分段控制器
@property (nonatomic, strong) UIButton *topBtn; //一键置顶按钮

@end

@implementation ArtTopicDetailListViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.start = 0;
    self.navigationItem.title = self.titleStr;
    self.navigationController.navigationBar.translucent = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:self.tableView];
    [self createTopBtn];
    [self.tableView registerNib:[UINib nibWithNibName:@"ArtTopicDetailListViewCell" bundle:nil] forCellReuseIdentifier:@"ArtTopicDetailListCELL"];
    
    if ( self.index == 0) {
        [self fenchDataSourceWithUrlString:kArtSpecialTopics parameter:nil];
        
        
    } if(self.index == 1){
        [self fenchDataSourceWithUrlString:kArtPgceTopic parameter:nil];
        [self creatMJRefreshAndLoadUrl:kArtPgceTopic];
        
    }
    if(self.index >= 2)
    {
        
        [self.view addSubview: self.selected];//添加自定义顶部分段控制器
        self.tableView.frame = CGRectMake(0, 30, kScreenWidth, kScreenHeight);
        [self.parameter setObject:self.timeRankMArr[self.index-2] forKey:@"_s"];
        [self.parameter setObject:self.categoryIdMArr[self.index-2] forKey:@"categoryId"];
        [self fenchDataSourceWithUrlString:kArtTopic parameter:self.parameter];
        [self creatMJRefreshAndLoadUrl:kArtTopic];//下拉刷新上拉加载
        __weak ArtTopicDetailListViewController *weakSelf = self;//使用__weak修饰self
        self.selected.selectedScrollViewPageBlock = ^(NSInteger index){//使用block传值
            
            if (index == 0) {
                
                [weakSelf.parameter setObject:weakSelf.timeRankMArr[weakSelf.index-2] forKey:@"_s"];
                [weakSelf.parameter setObject:weakSelf.categoryIdMArr[weakSelf.index-2] forKey:@"categoryId"];
                [weakSelf.parameter setObject:@"date" forKey:@"strategy"];
                [weakSelf fenchDataSourceWithUrlString:kArtTopic parameter:weakSelf.parameter];
                [weakSelf creatMJRefreshAndLoadUrl:kArtTopic];
            
            }else if (index == 1){
                
                [weakSelf.parameter setObject:weakSelf.shareRankingMArr[weakSelf.index-2] forKey:@"_s"];
                [weakSelf.parameter setObject:weakSelf.categoryIdMArr[weakSelf.index-2] forKey:@"categoryId"];
                [weakSelf.parameter setObject:@"shareCount" forKey:@"strategy"];
                [weakSelf fenchDataSourceWithUrlString:kArtTopic parameter:weakSelf.parameter];
                [weakSelf creatMJRefreshAndLoadUrl:kArtTopic];
                
            }
            
        };
    }
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


#pragma mark ---tableView代理方法---

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   
    return self.dataSourceMArr.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BaseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ArtTopicDetailListCELL" forIndexPath:indexPath];
    id mode = self.dataSourceMArr[indexPath.row];
    [cell setCellWithModel:mode];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 200;
}

//cell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ( self.index == 0)  {
        
        ArtTopicListModel *model = self.dataSourceMArr[indexPath.row];
        //        使用扫描类进行扫描
        NSScanner *scanner = [NSScanner scannerWithString:model.actionUrl];
        //       创建一个最终接受结果的字符串
        NSString *url = @"";
        //        给定一个http扫描条件进行扫描
        [scanner scanUpToString:@"http" intoString:nil];
        [scanner scanUpToString:@"" intoString:&url];
        //    将UTF8转换成中文
        NSString *strEncoder = [url stringByRemovingPercentEncoding];
        NSLog(@"strEncoder===%@", strEncoder);
        
        UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        GoOutSpecialTopicDetialViewController *goOutSpecialTopicDetialVC = [mainStoryboard instantiateViewControllerWithIdentifier:@"GoOutSpecialTopicDetialViewController"];
        goOutSpecialTopicDetialVC.htmlUrl = strEncoder;
        
        [self.navigationController pushViewController:goOutSpecialTopicDetialVC animated:YES];
        
    }else if (self.index == 1){
        
        UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        ArtTopicVideoViewController * artTopicVideoVC = [mainStoryboard instantiateViewControllerWithIdentifier:@"ArtTopicVideoViewController"];
        ArtTopDataModel *model = self.dataSourceMArr[indexPath.row];
        [artTopicVideoVC.dataSourceMArr addObject:model];
        [self.navigationController pushViewController:artTopicVideoVC animated:YES];
        
    }else if (self.index == 2){
        
        UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        ArtTopicVideoViewController * artTopicVideoVC = [mainStoryboard instantiateViewControllerWithIdentifier:@"ArtTopicVideoViewController"];
        ArtTopDataModel *model = self.dataSourceMArr[indexPath.row];
        [artTopicVideoVC.dataSourceMArr addObject:model];
        [self.navigationController pushViewController:artTopicVideoVC animated:YES];
        
    }

    
}


#pragma mark - 上拉加载下拉刷新
- (void)creatMJRefreshAndLoadUrl:(NSString *)urlStr {
//    上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //    重新设置加载条数
        self.start  += 10;
        [self.parameter setObject:@(self.start) forKey:@"start"];
        [self fenchDataSourceWithUrlString:urlStr parameter:self.parameter];
        [self.tableView reloadData];
        
    }];
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        //每次刷新之前将之前的数据移除
        if (self.dataSourceMArr.count != 0) {
            self.dataSourceMArr = nil;
        }
       [self fenchDataSourceWithUrlString:urlStr parameter:self.parameter];
        [self.tableView reloadData];
        
    }];
    
    
}

#pragma mark --请求数据--
- (void)fenchDataSourceWithUrlString:(NSString *)urlStr parameter:(NSMutableDictionary *)parameter {
    
    [LHDataRequestTools getFetchDataWithUrlString:urlStr paramenters:parameter success:^(id data) {
        
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        if ([urlStr isEqualToString:kArtSpecialTopics]) { //专题界面
            

            for (NSDictionary *dic in resultDic[@"itemList"]) {
                
                ArtTopicListModel *model = [[ArtTopicListModel alloc] init];
                [model setValuesForKeysWithDictionary:dic[@"data"]];
                [self.dataSourceMArr addObject:model];
            }
            
            
        }  if ([urlStr isEqualToString:kArtPgceTopic]) { //作者界面
            
            for (NSDictionary *dic in resultDic[@"pgcList"]) {
                
                for (NSDictionary *itemDic in dic[@"itemList"]) {
                    
                    if ([itemDic[@"type"] isEqualToString:@"video"]) {
                        
                        ArtTopDataModel *model = [[ArtTopDataModel alloc] init];
                        [model setValuesForKeysWithDictionary:itemDic[@"data"]];
                        [self.dataSourceMArr addObject:model];
                    }
                }
            }
            
        }
        if ([urlStr isEqualToString:kArtTopic]) {//创意等界面
//            [self.dataSourceMArr  removeAllObjects];
            
            for (NSDictionary *itemDic in resultDic[@"itemList"]) {
                
                if ([itemDic[@"type"] isEqualToString:@"video"]) {
                    
                    ArtTopDataModel *model = [[ArtTopDataModel alloc] init];
                    [model setValuesForKeysWithDictionary:itemDic[@"data"]];
                    
                    [self.dataSourceMArr addObject:model];
                }
            }
        }
        
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
   } fail:^{
       
        NSLog(@"话题列表请求失败");
    } view:self.view];

  
}

//一键置顶按钮,这个按钮必须加在视图最前端
- (void)createTopBtn{
    _topBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_topBtn setFrame:CGRectMake(30, kScreenHeight-100, 30, 30)];
    _topBtn.backgroundColor = [UIColor clearColor];
    [_topBtn setImage:[[UIImage imageNamed:@"top.jpg"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] forState:(UIControlStateNormal)];
    [_topBtn setTitle:@"返回" forState:UIControlStateNormal];
    [_topBtn addTarget:self action:@selector(topAction) forControlEvents:(UIControlEventTouchUpInside)];
    _topBtn.alpha = 0.8;
    //    让按钮放在父视图的顶部
    [self.view bringSubviewToFront:_topBtn];
    [self.view addSubview:_topBtn];
    
    
}
//然后让tableView的X，Y置为0
-(void)topAction{
   
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
}





#pragma mark --属性懒加载--

- (UITableView *)tableView{
    if (!_tableView) {
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

//创意界面按时间排行参数
-(NSMutableArray *)timeRankMArr{
    if (!_timeRankMArr) {
        
        _timeRankMArr = [[NSMutableArray alloc] initWithObjects:@"0ea765bbb1bc605f1faa40818532cde4",@"b1277e83553bd0da18a5cd0f77a21147",@"1f75d26c817d01ceaa5fafd5fbfebeb1",@"63e9c52a59c4d9dec68e7b593d0979c7",@"edd1fcffbe843f0d370fef9eea764125",@"74f4060603a88e32bdcc6cecf7733974",@"d816b80c17e133d1b0a25056a802df4c",@"2f7cf56230271f4a9f7e698dc0413368",@"32419f091abde1964868a23942fe9c1a",@"0390cb6d40f7762897bff5a62d4a0cb1",@"fb7d98d7208bfc2ff7a41b99035ad06e",@"c8b57b3c045e2b42df844afd9ddffaa6",nil];
    }
    return _timeRankMArr;
}

//创意界面按分享排行参数
-(NSMutableArray *)shareRankingMArr{
    
    if (!_shareRankingMArr) {
        
        _shareRankingMArr = [[NSMutableArray alloc] initWithObjects:@"45d26e56c95855c0238c8b006ca7ae67",@"9da82331e6f2ef193189534d915e1cfe",@"ad0e2e45dafc5c7d1dfa16708fa2cc14",@"2702cf597bf5e26c24a3c2e60f92b7ea",@"a502e8e433a06e0e5fbb5aef2ea2bff7",@"c495eb10c4737f2718a7627d75b4e175",@"512c02fbc332b0b0e9272124333c20ce",@"4955c69f9ad660750a787c27749ea3df",@"2bc8f990f92b4bc5cf7a3e944232cd79",@"0ea8f0042257e3dd0c3681a1a1440ad0",@"87cf9f44ee97f84a9ad50f85d37d8941",@"8343b65a637169c6da80feeff3824f6f", nil];
    }
    return _shareRankingMArr;
}


//categoryId数组
- (NSMutableArray *)categoryIdMArr{
    
    if (!_categoryIdMArr) {
        
        _categoryIdMArr = [[NSMutableArray alloc] initWithObjects:@"2",@"18",@"6",@"12",@"10",@"14",@"20",@"4",@"8",@"16",@"22",@"24", nil];
    }
    return _categoryIdMArr;
}

- (NSMutableArray *)dataSourceMArr{
    
    if (!_dataSourceMArr) {
        
        _dataSourceMArr = [NSMutableArray array];
    }
    return _dataSourceMArr;
}


- (NSMutableDictionary *)parameter {
    
    if (!_parameter) {
        
        _parameter = [[NSMutableDictionary alloc] initWithDictionary:@{@"start":@0,@"strategy":@"date"}];//默认是按时间排序
    }
    return _parameter;
}


//自定义顶部分段控制器
- (LHSelectedNavigationViewTools *)selected{
    
    if (!_selected) {
        
        _selected = [[LHSelectedNavigationViewTools alloc] initLHSelectedNavigationViewToolsWithFrame:CGRectMake(0, 0, 120, 30) ButtonTitle:[NSArray arrayWithObjects:@"按时间排序",@"按分享排序", nil]];
    }
    return _selected;
}


@end
